package com.playball.lottery.frm.score;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.fragment.frm.ScoreMainFragment;
import com.playball.lottery.util.DefConstants;
import com.playball.lottery.util.Logger;
import com.playball.lottery.util.MyPreference;

//import com.playball.lottery.R;
//import com.playball.lottery.tools.DateUtil;
//import com.playball.lottery.tools.DefConstants;
//import com.playball.lottery.tools.MyPreference;
//import com.playball.lottery.tools.ScoreUtil;
//import com.playball.lottery.view.buy.customview.ApplicationBall;
//import com.playball.lottery.view.hemai.HeMaiDetailActivity;

/**
 * 比分listview适配器
 * 
 * @author Administrator
 * 
 */
public class ScoreOnlineListAdapter extends BaseAdapter implements DefConstants{
	/** 运行上下文 */
	private Context context;
	/** 比分listview数据 */
	private List<Map<String, Object>> mData;
	private LayoutInflater mInflater;
	private OnAdapterChangeListener listener;
	/** 比分赛事类型 */
	private int matchState;
	/** 我的关注数量 */
	int focus;
	/**彩种类型*/
	int lotID;
	/**竞彩足球我的关注存储类sharedpreferences XML名字*/
	private String jczqfav="jczqfav";
	/**北单我的关注存储类sharedpreferences XML名字*/
	private String bdfav="bdfav";

	public ScoreOnlineListAdapter(Context context, List<Map<String, Object>> appData, int matchState,int lotid) {
		this.context = context;
		mData = appData;
		lotID=lotid;
//		Log.v("ScoreOnlineListAdapter", "构造器lotID= "+lotID);
		this.mInflater = LayoutInflater.from(context);
		// 赛事类型
		this.matchState = matchState;
		// 初始化数据
		for (int i = 0; i < appData.size(); i++) {
			appData.get(i).put("isLight", 0);
		}
	}

	/**
	 * 改变item背景,设置高亮
	 * @param pos 改变背景的那行
	 * @param data
	 */
	public void setLightOnData(List<Map<String, Object>> data, int pos) {
		if(data!=null){
			for (int i = 0; i < data.size(); i++) {
				if (i == pos) {
					data.get(i).put("isLight", 1);
				}
			}
		this.mData = data;
		}
	}

	/**
	 * 设置不亮
	 * 
	 * @param data
	 */
	public void setLightOffData(List<Map<String, Object>> data) {
		if(data!=null){
			for (int i = 0; i < data.size(); i++) {
				data.get(i).put("isLight", 0);
			}
			this.mData = data;
		}
	}

	public void setOnAdapterChangeListener(OnAdapterChangeListener listener) {
		this.listener = listener;
	}

	public int getCount() {
		return mData.size();
	}

	public Object getItem(int arg0) {
		return mData.get(arg0);
	}

	public long getItemId(int arg0) {
		return arg0;
	}

	public View getView(final int position, View convertView, final ViewGroup parent) {
		// System.out.println("getView " + position + " " + convertView);
		ViewHolder holder = null;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = mInflater.inflate(R.layout.score_list_item, null);
			holder.llLeft = (LinearLayout) convertView.findViewById(R.id.score_ll_right1);
//			holder.llRight = (LinearLayout) convertView.findViewById(R.id.score_ll_right);
			holder.ivstar = (ImageView) convertView.findViewById(R.id.score_iv_star_focus);
			holder.name = (TextView) convertView.findViewById(R.id.score_list_match_name);
			holder.time = (TextView) convertView.findViewById(R.id.score_list_begin_time);
			holder.state = (TextView) convertView.findViewById(R.id.score_list_match_state);
			// holder.play = (TextView)
			// convertView.findViewById(R.id.score_list_match_play);
			// 半场比分
			holder.bscore = (TextView) convertView.findViewById(R.id.score_list_match_splay);
			holder.hteam = (TextView) convertView.findViewById(R.id.score_list_match_hteam);
			holder.hteam_yellow = (TextView) convertView.findViewById(R.id.score_list_match_hteam_yellow);
			holder.hteam_red = (TextView) convertView.findViewById(R.id.score_list_match_hteam_red);
			holder.currscore = (TextView) convertView.findViewById(R.id.score_list_match_curr_score);
			holder.vteam = (TextView) convertView.findViewById(R.id.score_list_match_vteam);
			holder.vteam_red = (TextView) convertView.findViewById(R.id.score_list_match_vteam_red);
			holder.vteam_yellow = (TextView) convertView.findViewById(R.id.score_list_match_vteam_yellow);

			convertView.setTag(holder);

		} else {

			holder = (ViewHolder) convertView.getTag();
		}
		// 赛事简称,超过3个字符的，后面去掉
		String shortName = String.valueOf(mData.get(position).get("i2"));
		if (shortName.length() > 3) {
			if (shortName.substring(0, 3).endsWith("-")) {
				holder.name.setText(shortName.substring(0, 2) + "...");
			} else {
				holder.name.setText(shortName.substring(0, 3) + "...");
			}
		} else {// 字符长度小于3位，不用截取
			holder.name.setText(shortName);
		}
		// 日期
		String time = String.valueOf(mData.get(position).get("i3"));
//		String[] arrs = time.split(" ");
//		String[] dates = arrs[0].split("\\-");
//		if (dates.length == 2) {
//			String showdate = dates[1] + "日" + arrs[1];
//			holder.time.setText(showdate);
//		}
		holder.time.setText(time);
		
		// 半场比分,如果未开赛状态显示空，否则显示实际半场比分或0-0
		if("未".equals(String.valueOf(mData.get(position).get("i4")))||"延".equals(String.valueOf(mData.get(position).get("i4")))||"推迟开赛".equals(String.valueOf(mData.get(position).get("i4")))){
			holder.bscore.setText(" ");
		}else{
			holder.bscore.setText("上半场 " + String.valueOf(mData.get(position).get("i13")).replace(":", "-"));
		}

		//状态
		holder.state.setText(String.valueOf(mData.get(position).get("i4")));
		// holder.play.setText((String.valueOf(mData.get(position).get("i1"))));
		// 对主队名字过长时进行截取处理
		String hostname = String.valueOf(mData.get(position).get("i5"));
		if (hostname.length() > 4) {
//			if (hostname.substring(0, 5).endsWith("-")) {
//				holder.hteam.setText(hostname.substring(0, 4) + "...");
//			} else {
//				holder.hteam.setText(hostname.substring(0, 5) + "...");
//			}
			holder.vteam.setText(hostname.substring(0, 4));
		} else {// 字符长度小于6位，不用截取
			holder.hteam.setText(hostname);
		}
		// 主队红牌数
		if (String.valueOf(mData.get(position).get("i6")).equals("0")) {
			holder.hteam_red.setVisibility(View.GONE);
		} else {
			holder.hteam_red.setVisibility(View.VISIBLE);
			holder.hteam_red.setText(String.valueOf(mData.get(position).get("i6")));
		}
		// 主队黄牌数
		if (String.valueOf(mData.get(position).get("i7")).equals("0")) {
			holder.hteam_yellow.setVisibility(View.GONE);
		} else {
			holder.hteam_yellow.setVisibility(View.VISIBLE);
			holder.hteam_yellow.setText(String.valueOf(mData.get(position).get("i7")));
		}
		// 主队分数:客队分数i8-i12   比分  如果未开赛状态显示-，否则显示实际比分，或0-0
		if("未".equals(String.valueOf(mData.get(position).get("i4")))||"延".equals(String.valueOf(mData.get(position).get("i4")))||"推迟开赛".equals(String.valueOf(mData.get(position).get("i4")))){
			holder.currscore.setText("-");
		}else{
			holder.currscore.setText(String.valueOf(mData.get(position).get("i8")) + "-" + String.valueOf(mData.get(position).get("i12")));
		}

		// 对客队名字过长时进行截取处理
		String vename = String.valueOf(mData.get(position).get("i9"));
		if (vename.length() > 4) {
//			if (vename.substring(0, 5).endsWith("-")) {
//				holder.vteam.setText(vename.substring(0, 4) + "...");
//			} else {
//				holder.vteam.setText(vename.substring(0, 5) + "...");
//			}
			holder.vteam.setText(vename.substring(0, 4));
		} else {// 字符长度小于6位，不用截取
			holder.vteam.setText(vename);
		}
		// 客队红牌数
		if (String.valueOf(mData.get(position).get("i10")).equals("0")) {
			holder.vteam_red.setVisibility(View.GONE);
		} else {
			holder.vteam_red.setVisibility(View.VISIBLE);
			holder.vteam_red.setText(String.valueOf(mData.get(position).get("i10")));
		}
		// 客队黄牌数
		if (String.valueOf(mData.get(position).get("i11")).equals("0")) {
			holder.vteam_yellow.setVisibility(View.GONE);
		} else {
			holder.vteam_yellow.setVisibility(View.VISIBLE);
			holder.vteam_yellow.setText(String.valueOf(mData.get(position).get("i11")));
		}
		
		 //Here comes the magic
//		convertView.setSelected(items[position].selected);

//	    convertView.setBackgroundResource((convertView.isSelected()) ? R.drawable.score_list_item_bg2hover : R.drawable.score_list_item_bg2);
		
		// 关注按钮点击与否
//		if(mData.get(position)==null){
//		Log.e("sadapter", "mData.get(position)==null");
//		}
//		if(mData.get(position).get("isCheck")==null){
//			Log.e("sadapter", "mData.get(position).get(isCheck)==null");
//		}
			if ((Integer) mData.get(position).get("isCheck") == 0) {
				holder.ivstar.setBackgroundResource(R.drawable.score_star1);
			} else {
				holder.ivstar.setBackgroundResource(R.drawable.score_star2);
			}

		
		holder.llLeft.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// Log.i("llLeft",
				// "llLeft.setOnClickListener mData.size()= "+mData.size()+
				// " ,position= "+position);
				// 如果用户在我的关注下，狂点击取消关注，程序还没有运行完毕
				if (mData.size() <= position) {
					// Log.e("llLeft", "mData.size()<=position");
					return;
				}
				if ((Integer) mData.get(position).get("isCheck") == 0) {
					Map<String, Object> selectMap = new HashMap<String, Object>();
					// 添加选择de数据
					selectMap.put("i1", String.valueOf(mData.get(position).get("i1")));
					selectMap.put("i2", String.valueOf(mData.get(position).get("i2")));
					selectMap.put("i3", String.valueOf(mData.get(position).get("i3")));
					selectMap.put("i4", String.valueOf(mData.get(position).get("i4")));
					selectMap.put("i5", String.valueOf(mData.get(position).get("i5")));
					selectMap.put("i6", String.valueOf(mData.get(position).get("i6")));
					selectMap.put("i7", String.valueOf(mData.get(position).get("i7")));
					selectMap.put("i8", String.valueOf(mData.get(position).get("i8")));
					selectMap.put("i9", String.valueOf(mData.get(position).get("i9")));
					selectMap.put("i10", String.valueOf(mData.get(position).get("i10")));
					selectMap.put("i11", String.valueOf(mData.get(position).get("i11")));
					selectMap.put("i12", String.valueOf(mData.get(position).get("i12")));
					selectMap.put("i13", String.valueOf(mData.get(position).get("i13")));
					selectMap.put("isCheck", 1);
					// 保存当前时间
//					selectMap.put("fustime", DateUtil.getFullDateTime());
					// 改变按钮状态
					mData.get(position).put("isCheck", 1);
					// 添加关注
					AddFocus(selectMap);
					// Toast.LENGTH_SHORT).show();
					showTextToast("成功添加我的关注");
				} else if ((Integer) mData.get(position).get("isCheck") == 1) {
					Map<String, Object> selectMap = new HashMap<String, Object>();
					// 添加选择de数据
					selectMap.put("i1", String.valueOf(mData.get(position).get("i1")));
					selectMap.put("i2", String.valueOf(mData.get(position).get("i2")));
					selectMap.put("i3", String.valueOf(mData.get(position).get("i3")));
					selectMap.put("i4", String.valueOf(mData.get(position).get("i4")));
					selectMap.put("i5", String.valueOf(mData.get(position).get("i5")));
					selectMap.put("i6", String.valueOf(mData.get(position).get("i6")));
					selectMap.put("i7", String.valueOf(mData.get(position).get("i7")));
					selectMap.put("i8", String.valueOf(mData.get(position).get("i8")));
					selectMap.put("i9", String.valueOf(mData.get(position).get("i9")));
					selectMap.put("i10", String.valueOf(mData.get(position).get("i10")));
					selectMap.put("i11", String.valueOf(mData.get(position).get("i11")));
					selectMap.put("i12", String.valueOf(mData.get(position).get("i12")));
					selectMap.put("i13", String.valueOf(mData.get(position).get("i13")));
					selectMap.put("isCheck", 0);
					// 保存当前时间
//					selectMap.put("fustime", DateUtil.getFullDateTime());
					// 改变按钮状态
					mData.get(position).put("isCheck", 0);
					// 取消关注
					CancelFocus(selectMap);
					// Toast.LENGTH_SHORT).show();
					showTextToast("已取消关注");
					// 取消关注时，删除当前选中项
					if (mData.size() >= 1 && matchState == 4) {
						int p = position;
						mData.remove(p);
						if (listener != null) {
							// Log.e("llLeft.setOnClickListener", "listRemove");
							listener.listRemove(p);
						}
					}
				}
				// 重新调用getview，不要在此事件直接设置组件的显示
				notifyDataSetChanged();
			}
		});

//		holder.llRight.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				// Log.v("ad", "llRight click");
//				// // 跳转到详情页面
//				// Intent intent = new Intent();
//				// intent.setClass(context, HeMaiDetailActivity.class);
//				// Bundle mBundle = new Bundle();
//				// mBundle.putString("SID",
//				// String.valueOf(mData.get(position).get("SID")));// 压入数据:方案ID
//				// context.startActivity(intent);
//			}
//		});
		//进球选项背景
//		if ((Integer) mData.get(position).get("isLight") == 0) {
//			convertView.setBackgroundResource(R.drawable.score_list_item_bg2);
////			convertView.setBackgroundColor(context.getResources().getColor(R.color.white));
//		} else  {
//			convertView.setBackgroundResource(R.drawable.score_list_item_bg2hover);
////			convertView.setBackgroundColor(context.getResources().getColor(R.color.score_orange));
//		}

		return convertView;
	}

	public static class ViewHolder {
		public TextView name;
		public TextView time;
		public TextView state;
		// public TextView play;
		// 半场比分
		public TextView bscore;
		public TextView hteam;
		public TextView hteam_yellow;
		public TextView hteam_red;
		public TextView currscore;
		public TextView vteam;
		public TextView vteam_red;
		public TextView vteam_yellow;
		// 左侧布局
		public LinearLayout llLeft;
		// 右侧布局
		public LinearLayout llRight;
		public ImageView ivstar;
	}

	/**
	 * 添加关注
	 */
	public void AddFocus(Map<String, Object> selectMap) {
		if(lotID==LOT_ID_JCZQ){
			// 读存贮数据，比较以便不重复
			List<Map<String, Object>> Favlist = new ArrayList<Map<String, Object>>();
			Favlist = MyPreference.getInstance(context).getStringArrayPreflist2(context, jczqfav,"jczqfavoritos");
			Favlist.add(selectMap);
			focus=Favlist.size();
			//改变关注数量值
//			ScoreOnlineActivity.changeFocusNum(focus);
			ScoreMainFragment.changeFocusNum(focus);
			// 存贮
			MyPreference.getInstance(context).setStringArrayPreflist2(context, jczqfav,"jczqfavoritos", Favlist);
		}else if(lotID==LOT_ID_BD){
			// 读存贮数据，比较以便不重复
			List<Map<String, Object>> Favlist = new ArrayList<Map<String, Object>>();
			Favlist = MyPreference.getInstance(context).getStringArrayPreflist2(context,bdfav, "bdfavoritos");
			Favlist.add(selectMap);
			focus=Favlist.size();
			//改变关注数量值
//			ScoreOnlineActivity.changeFocusNum(focus);
			ScoreMainFragment.changeFocusNum(focus);
			// 存贮
			MyPreference.getInstance(context).setStringArrayPreflist2(context, bdfav,"bdfavoritos", Favlist);
		}
//		// 读存贮数据，比较以便不重复
//		List<Map<String, Object>> Favlist = new ArrayList<Map<String, Object>>();
//		Favlist = MyPreference.getInstance(context).getStringArrayPref2(context, "favoritos");
//		Favlist.add(selectMap);
//		focus=Favlist.size();
//		//改变关注数量值
//		ScoreOnlineActivity.changeFocusNum(focus);
//		// 存贮
//		MyPreference.getInstance(context).setStringArrayPref2(context, "favoritos", Favlist);
	}

	/**
	 * 取消关注
	 */
	public void CancelFocus(Map<String, Object> selectMap) {
		if(lotID==LOT_ID_JCZQ){
			// 删除：循环sharedpreferences中的这个值。用一个for循环。如果在sharedpreferences中匹配到了这个值，那么记录下for循环中当前循环的值。
			// 之后使用sharedpreferences删除方法根据这个for循环的值来删除sharedpreferences中保存的这个数据
			List<Map<String, Object>> FaviList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> NewList = new ArrayList<Map<String, Object>>();
			FaviList = MyPreference.getInstance(context).getStringArrayPreflist2(context,jczqfav, "jczqfavoritos");
			// 判断Favlist是否包含selectList,通过i1值
			if (FaviList != null) {
				for (int i = 0; i < FaviList.size(); i++) {
					String selI1 = String.valueOf(selectMap.get("i1"));
					if (!selI1.equals(String.valueOf(FaviList.get(i).get("i1")))) {
						Map<String, Object> NewMap = new HashMap<String, Object>();
						// 筛选数据
						NewMap.put("i1", FaviList.get(i).get("i1"));
						NewMap.put("i2", FaviList.get(i).get("i2"));
						NewMap.put("i4", FaviList.get(i).get("i4"));
						NewMap.put("i3", FaviList.get(i).get("i3"));
						NewMap.put("i5", FaviList.get(i).get("i5"));
						NewMap.put("i6", FaviList.get(i).get("i6"));
						NewMap.put("i7", FaviList.get(i).get("i7"));
						NewMap.put("i8", FaviList.get(i).get("i8"));
						NewMap.put("i9", FaviList.get(i).get("i9"));
						NewMap.put("i10", FaviList.get(i).get("i10"));
						NewMap.put("i11", FaviList.get(i).get("i11"));
						NewMap.put("i12", FaviList.get(i).get("i12"));
						NewMap.put("i13", FaviList.get(i).get("i13"));
						NewMap.put("isCheck", FaviList.get(i).get("isCheck"));
						// 保存当前时间
//						selectMap.put("fustime", FaviList.get(i).get("fustime"));
						// Log.e("CancelFocus", "NewMap= " + NewMap.toString());
						NewList.add(NewMap);
					}
				}
			}
			focus=NewList.size();
			//改变关注数量值
//			ScoreOnlineActivity.changeFocusNum(focus);
			ScoreMainFragment.changeFocusNum(focus);
			// 刷新存贮
			MyPreference.getInstance(context).setStringArrayPreflist2(context,jczqfav ,"jczqfavoritos", NewList);
		}else if(lotID==LOT_ID_BD){
			// 删除：循环sharedpreferences中的这个值。用一个for循环。如果在sharedpreferences中匹配到了这个值，那么记录下for循环中当前循环的值。
			// 之后使用sharedpreferences删除方法根据这个for循环的值来删除sharedpreferences中保存的这个数据
			List<Map<String, Object>> FaviList = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> NewList = new ArrayList<Map<String, Object>>();
			FaviList = MyPreference.getInstance(context).getStringArrayPreflist2(context, bdfav,"bdfavoritos");
			// 判断Favlist是否包含selectList,通过i1值
			if (FaviList != null) {
				for (int i = 0; i < FaviList.size(); i++) {
					String selI1 = String.valueOf(selectMap.get("i1"));
					if (!selI1.equals(String.valueOf(FaviList.get(i).get("i1")))) {
						Map<String, Object> NewMap = new HashMap<String, Object>();
						// 筛选数据
						NewMap.put("i1", FaviList.get(i).get("i1"));
						NewMap.put("i2", FaviList.get(i).get("i2"));
						NewMap.put("i4", FaviList.get(i).get("i4"));
						NewMap.put("i3", FaviList.get(i).get("i3"));
						NewMap.put("i5", FaviList.get(i).get("i5"));
						NewMap.put("i6", FaviList.get(i).get("i6"));
						NewMap.put("i7", FaviList.get(i).get("i7"));
						NewMap.put("i8", FaviList.get(i).get("i8"));
						NewMap.put("i9", FaviList.get(i).get("i9"));
						NewMap.put("i10", FaviList.get(i).get("i10"));
						NewMap.put("i11", FaviList.get(i).get("i11"));
						NewMap.put("i12", FaviList.get(i).get("i12"));
						NewMap.put("i13", FaviList.get(i).get("i13"));
						NewMap.put("isCheck", FaviList.get(i).get("isCheck"));
						// 保存当前时间
//						selectMap.put("fustime", FaviList.get(i).get("fustime"));
						// Log.e("CancelFocus", "NewMap= " + NewMap.toString());
						NewList.add(NewMap);
					}
				}
			}
			focus=NewList.size();
			//改变关注数量值
//			ScoreOnlineActivity.changeFocusNum(focus);
			ScoreMainFragment.changeFocusNum(focus);
			// 刷新存贮
			MyPreference.getInstance(context).setStringArrayPreflist2(context, bdfav,"bdfavoritos", NewList);
		}

	}

	public interface OnAdapterChangeListener {
		/**
		 * 删除我的关注当前选中项
		 * 
		 * @param currentItem
		 *            当前项
		 */
		public void listRemove(int currentItem);
	}

	private Toast toast = null;

	/**
	 * Toast重复显示问题解决
	 * 
	 * @param msg
	 */
	private void showTextToast(String msg) {
		if (toast == null) {
			toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
		} else {
			toast.setText(msg);
		}
		toast.show();
	}
	/**
	 * 判断字符串是否是数字
	 * @param str 字符串
	 * @return
	 */
	public static boolean isNum(String str){
		return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
	}

}
